<?php
// 显示所有错误
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 加载数据库配置
require_once __DIR__ . '/../config/database.php';

$message = '';
$success = false;

try {
    // 创建PDO连接
    $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
    $pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $message .= "数据库连接成功！<br>";
    
    // 检查用户表是否存在
    $tableExists = $pdo->query("SHOW TABLES LIKE '".DB_PREFIX."users'")->rowCount() > 0;
    
    if (!$tableExists) {
        // 创建用户表
        $pdo->exec("CREATE TABLE IF NOT EXISTS `".DB_PREFIX."users` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `username` varchar(50) NOT NULL,
          `password` varchar(255) NOT NULL,
          `email` varchar(100) NOT NULL,
          `nickname` varchar(50) DEFAULT NULL,
          `avatar` varchar(255) DEFAULT NULL,
          `role` enum('user','admin') NOT NULL DEFAULT 'user',
          `status` enum('active','inactive') NOT NULL DEFAULT 'active',
          `created_at` datetime NOT NULL,
          `updated_at` datetime NOT NULL,
          `last_login` datetime DEFAULT NULL,
          PRIMARY KEY (`id`),
          UNIQUE KEY `username` (`username`),
          UNIQUE KEY `email` (`email`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        
        $message .= "用户表成功创建！<br>";
    } else {
        $message .= "用户表已存在！<br>";
    }
    
    // 检查是否已存在管理员用户
    $checkAdmin = $pdo->query("SELECT COUNT(*) FROM `".DB_PREFIX."users` WHERE role = 'admin'");
    $adminCount = $checkAdmin->fetchColumn();
    
    if ($adminCount > 0) {
        $message .= "数据库中已存在 {$adminCount} 个管理员账户。<br>";
        
        // 查看现有管理员信息
        $adminUsers = $pdo->query("SELECT id, username, email, role, status FROM `".DB_PREFIX."users` WHERE role = 'admin'")->fetchAll(PDO::FETCH_ASSOC);
        
        $message .= "<h3>现有管理员账户：</h3>";
        $message .= "<ul>";
        foreach ($adminUsers as $admin) {
            $message .= "<li>ID: {$admin['id']}, 用户名: {$admin['username']}, 邮箱: {$admin['email']}, 状态: {$admin['status']}</li>";
        }
        $message .= "</ul>";
        
        // 询问是否重新创建
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['confirm_recreate']) && $_POST['confirm_recreate'] === 'yes') {
            $message .= "根据确认，将重新创建管理员账户...<br>";
        } else {
            $message .= "<form method='post'>";
            $message .= "是否重新创建管理员账户？这将删除所有现有的管理员账户。<br>";
            $message .= "<input type='hidden' name='confirm_recreate' value='yes'>";
            $message .= "<button type='submit' style='margin-top: 10px;'>确认重新创建</button>";
            $message .= "</form>";
            echo "<!DOCTYPE html><html><head><title>创建管理员账户</title></head><body>{$message}</body></html>";
            exit;
        }
    }
    
    // 如果需要重新创建或尚未存在管理员
    $message .= "开始创建新的管理员账户...<br>";
    
    // 删除所有现有的管理员账户
    $pdo->exec("DELETE FROM `".DB_PREFIX."users` WHERE role = 'admin'");
    $message .= "已删除所有现有的管理员账户。<br>";
    
    // 创建新的管理员账户
    $admin_username = 'admin';
    $admin_password = 'admin123';
    $admin_email = 'admin@example.com';
    
    // 生成新的密码哈希
    $password_hash = password_hash($admin_password, PASSWORD_DEFAULT);
    
    // 插入新管理员账户
    $stmt = $pdo->prepare("INSERT INTO `".DB_PREFIX."users` 
        (username, password, email, role, status, created_at, updated_at) 
        VALUES (?, ?, ?, 'admin', 'active', NOW(), NOW())");
    $result = $stmt->execute([$admin_username, $password_hash, $admin_email]);
    
    if ($result) {
        $message .= "<h3>管理员账户创建成功！</h3>";
        $message .= "用户名: {$admin_username}<br>";
        $message .= "密码: {$admin_password}<br>";
        $message .= "邮箱: {$admin_email}<br>";
        $message .= "密码哈希: {$password_hash}<br>";
        $message .= "请使用上述信息登录管理后台。";
        $success = true;
    } else {
        $message .= "管理员账户创建失败！";
    }
    
    // 验证密码哈希
    $message .= "<h3>密码验证测试：</h3>";
    $verify_result = password_verify($admin_password, $password_hash);
    $message .= "密码验证结果: " . ($verify_result ? "通过" : "失败") . "<br>";
    
    // 验证SQL查询
    $admin = $pdo->query("SELECT * FROM `".DB_PREFIX."users` WHERE username = '{$admin_username}'")->fetch(PDO::FETCH_ASSOC);
    if ($admin) {
        $message .= "可以通过SQL查询到管理员账户！<br>";
        $sql_verify = password_verify($admin_password, $admin['password']);
        $message .= "SQL查询的密码验证结果: " . ($sql_verify ? "通过" : "失败") . "<br>";
    } else {
        $message .= "SQL查询无法找到管理员账户！<br>";
    }
    
} catch (PDOException $e) {
    $message .= "<h3>错误：</h3>";
    $message .= $e->getMessage();
}

// 输出结果
echo "<!DOCTYPE html>
<html>
<head>
    <title>创建管理员账户</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .success { color: green; font-weight: bold; }
        .error { color: red; font-weight: bold; }
        pre { background-color: #f5f5f5; padding: 10px; border-radius: 5px; }
        a.button { 
            display: inline-block;
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            text-decoration: none;
            border-radius: 5px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <h1>创建管理员账户</h1>
    <div class='" . ($success ? "success" : "error") . "'>
        {$message}
    </div>";

if ($success) {
    echo "<a href='login.php' class='button'>返回登录页面</a>";
}

echo "</body>
</html>";
?> 